package com.daocao.hua.http;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;

import com.daocao.hua.R;
import com.daocao.hua.constant.Const;
import com.daocao.hua.model.RequestModel;
import com.daocao.hua.util.CryptAES;
import com.daocao.hua.util.JsonUtil;
import com.daocao.hua.util.KeyHandler;
import com.daocao.hua.util.RBLog;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Master.Dong on 2016/4/11.
 */
public class InterfaceServer {
    private static final String TAG = "dob";

//    private static LogUtil log = null;
//
//    {
//        log = LogUtil.getInstance(this.getClass());
//    }

    private NetStatus netStatus = null;  //网络状态
    private int versionCode = 0;  //版本号

    private static Context applicationContext;
    private static InterfaceServer instance = null;

    private Map<String, String> requestProperties = null;

    private static Handler handler = new Handler(Looper.getMainLooper());

    private static void postRunable(Runnable r) {
        handler.post(r);
    }

    private InterfaceServer(Context applicationContext) {
        netStatus = NetStatus.getInstance(applicationContext);
//        versionCode = PackageUtil.getVersionCode(applicationContext.getApplicationContext());
        this.applicationContext = applicationContext;
    }

    /**
     * 获取单例
     *
     * @return
     */
    public static synchronized InterfaceServer getInstance(Context context) {
        if (instance == null) {
            instance = new InterfaceServer(context.getApplicationContext());
        }
        return instance;
    }

//    /**
//     * 请求数据接口
//     *
//     * @param model
//     * @param responseListener
//     */
//    public void requestInterface(final String url, final int requestMethod, final RequestModel model, final int timeOut, final ResponseListener responseListener) {
//        new Thread() {
//            public void run() {
//                if (netStatus.isNetowrkAvaiable(Const.DEFAULT_TIMEOUT)) {
//                    try {
//                        if (model != null) {
//                            // TODO MKK
//                            // RequestParams requestParams = getRequestParamsNoJson(model);
//                            // RequestParams requestParams = getRequestParams(model);
//
//                            String requestData = getStrParams(model);
////                            int i_type = model.getmRequestDataType();
////                            int r_type = model.getmResponseDataType();
////                            String dev_type = Const.DevType.ANDROID;
////                            int version = versionCode;
//
////                            RBLog.i("request-----------------", requestData);
//
//                            // TODO
//                            //printRequestUrl(model);
////                            String apiUrl = Const.SERVER_API_URL;
//
//                            HttpUtil http = HttpUtil.getInstance(applicationContext);
//
//                            long connectTimeout = timeOut;
//                            long readTimeout = timeOut;
//
//                            List<String> reses = null; //返回结果
//
//                            switch (requestMethod) {
//                                case Const.RequestMethod.GET:
//                                    requestProperties = http.getDefaultRequestProperties();
//                                    StringBuffer strParams = new StringBuffer();
////                                    strParams.append("client_type=app");
////                                    strParams.append("&device_id=" + Util.getDeviceId(applicationContext));
////
////                                    strParams.append("&os=" + dev_type);
////                                    strParams.append("&app_version=" + version);
//                                    strParams.append("" + requestData);
//                                    reses = http.doGet(url + "?" + strParams.toString(), requestProperties, connectTimeout, readTimeout);
//                                    break;
//                                case Const.RequestMethod.POST:
//                                    requestProperties = http.getDefaultRequestProperties();
//                                    Map<String, String> requestParameters = new HashMap<String, String>();
////                                    requestParameters.put("i_type", String.valueOf(i_type));
////                                    requestParameters.put("r_type", String.valueOf(r_type));
////                                    requestParameters.put("os", dev_type);
////                                    requestParameters.put("app_version", String.valueOf(version));
//                                    requestParameters.put("", requestData);
//                                    reses = http.doPost(url, requestProperties, requestParameters, connectTimeout, readTimeout);
//                                    break;
//                                default:
//                                    postRunable(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            responseListener.onFinishInMainThread(null);
//                                        }
//                                    });
//                                    break;
//                            }
//
//                            StringBuffer strRes = new StringBuffer();
//                            if (reses != null) {
//                                for (String res : reses) {
//                                    strRes.append(res);
//                                }
//                            }
//
//                            if (strRes.toString().length() >= 0) {
////                                final String content = parseResult(model, strRes.toString());   //  暂时不用解密
//                                final String content = strRes.toString();
//                                final int statusCode = 0; //无用，暂时保留
////                                RBLog.i(" 返回数据 ----- ", content);
//                                final Object result = responseListener.onSuccessInRequestThread(statusCode, content);
//                                postRunable(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if (result == null) {
//                                            responseListener.onStartInMainThread(applicationContext.getResources().getString(R.string.get_data_error));
//                                        } else
//                                            responseListener.onSuccessInMainThread(statusCode, content, result);
//                                    }
//                                });
//                            }
//
//                        }// End of if(model == null)
//
//                    } catch (Exception e) {
//                        RBLog.e("", e.getMessage());
//                    } finally {
//                        postRunable(new Runnable() {
//                            @Override
//                            public void run() {
//                                responseListener.onFinishInMainThread(null);
//                            }
//                        });
//                    }
//
//                } else {
//                    //log.show("当前网络不可用!");
//
//                    postRunable(new Runnable() {
//                        @Override
//                        public void run() {
////                            ToastUtil.makeText(applicationContext.getApplicationContext(), applicationContext.getResources().getString(R.string.check_network_text), Toast.LENGTH_SHORT).show();
//                            responseListener.onStartInMainThread(applicationContext.getResources().getString(R.string.check_network_text));
//                        }
//                    });
//                }
//            }
//        }.start();
//    }

    /**
     * 请求数据接口
     *
     * @param model
     * @param responseListener
     */
    public void requestInterface(final String url, final int requestMethod, final RequestModel model, final int timeOut, final ResponseListener responseListener) {
        if (netStatus.isNetworkAvailable()) {
            Callback callback = new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        final String resultStr = response.body().string();
                        Log.d(TAG, "result=" + resultStr);

                        final int statusCode = 0; //无用，暂时保留
                        final Object result = responseListener.onSuccessInRequestThread(statusCode, resultStr);
                        postRunable(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (result == null) {
                                            responseListener.onStartInMainThread(applicationContext.getResources().getString(R.string.get_data_error));
                                        } else
                                            responseListener.onSuccessInMainThread(statusCode, resultStr, result);
                                    }
                                });
                    }
                }
            };

            String json = getStrParams(model);
            switch (requestMethod) {
                case Const.RequestMethod.GET:
                    HttpUtil.get(url + "?" + getStrParams(model).toString(),callback );
                    break;
                case Const.RequestMethod.POST:
//                    FormBody.Builder builder = new FormBody.Builder();
//                    Map<String, Object> map = (Map) model.getmData();
//                    for (String key : map.keySet()) {
//                        builder.add(key, map.get(key).toString());
//                    }


                    HttpUtil.post(url, json, callback);
                    break;
                default:
                    responseListener.onFinishInMainThread(null);
                    break;
            }
        }else {
            responseListener.onStartInMainThread(applicationContext.getResources().getString(R.string.check_network_text));
        }
    }


    /**
     * 获取请求数据串
     *
     * @param model
     * @return
     */
    private String getStrParams(RequestModel model) {
        String keyStr = KeyHandler.getInstance().getKey();
        String requestData = JsonUtil.toJson(model.getmData());
//        switch (model.getmRequestDataType()) {
//            case Const.RequestDataType.REQUEST:
//                // requestData = JsonUtil.toJson(model.getmData());
//                break;
//            case Const.RequestDataType.BASE64:
//                try {
//                    requestData = new String(Base64.encode(requestData.getBytes("UTF-8"), Base64.DEFAULT), "UTF-8");
//                } catch (UnsupportedEncodingException e) {
//                    RBLog.e("", e.getMessage());
//                }
//                break;
//            case Const.RequestDataType.AES:
//                try {
//                    requestData = CryptAES.AES_Encrypt(keyStr, requestData);
//                } catch (Exception e) {
//                    RBLog.e("", e.getMessage());
//                }
//                break;
//            default:
//                break;
//        }
        return requestData.equals("{}") ? "" : requestData;  //判断请求是否为空
    }


    /**
     * 获取返回数据串
     *
     * @param model
     * @return
     */
    private String parseResult(RequestModel model, String result) {
        String keyStr = KeyHandler.getInstance().getKey();

        String responseData = result;
        switch (model.getmRequestDataType()) {
            case Const.RequestDataType.REQUEST:
                // responseData = result;
                break;
            case Const.RequestDataType.BASE64:
                try {
                    responseData = new String(Base64.decode(responseData.getBytes("UTF-8"), Base64.DEFAULT), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    RBLog.e("", e.getMessage());
                }
                break;
            case Const.RequestDataType.AES:
                try {
                    responseData = CryptAES.AES_Decrypt(keyStr, responseData);
                } catch (Exception e) {
                    RBLog.e("", e.getMessage());
                }
                break;
            default:
                break;
        }

        //设置新密钥
//        try {
//            ResponseModel respModel = JsonUtil.fromJson(responseData, ResponseModel.class);
//            if (!"".equals(respModel.getNew_key())) {
//                KeyHandler.getInstance().setKey(respModel.getNew_key());
//                KeyHandler.getInstance().setDefaultKey(false);
//            }
//        } catch (Exception e) {
//            RBLog.e("", e.getMessage());
//        }

        return responseData;
    }

    /**
     * 返回结果是否正确
     *
     * @param model
     * @return
     */
//    public static boolean isResponseValid(Object model) {
//        if (model != null) {
//            ResponseModel nModel = (ResponseModel) model;
//            if (nModel.getShow_err() != null && !"".equals(nModel.getShow_err().trim())) {
////                log.show(nModel.getShow_err());
//            }
//            return true;
//        } else {
//            ToastUtil.makeText(applicationContext, applicationContext.getResources().getString(R.string.serve_busy_text), Toast.LENGTH_SHORT).show();
//        }
//        return false;
//    }

}
